def createBackupTable(conn,tablename):
	try:
		cursor = conn.cursor()
		cursor.execute("select * from ypb_"+tablename)
	except BaseException: #no table named xxx,so create it!
		print("no table named 'ypb_"+tablename+"',will create it")
		cursor = conn.cursor()
		cursor.execute("select * into ypb_"+tablename+" from "+tablename)
		conn.commit()
		print("create table success!")
def createBackupTrigger(conn,tablename):
	triggerName = "ypb_"+tablename+"_tigger()"
	funsql = "CREATE OR REPLACE FUNCTION "+triggerName+" RETURNS TRIGGER AS $$ BEGIN "
	funsql += " INSERT INTO ypb_"+tablename+" VALUES(NEW.*);"
	funsql += "RETURN null;  END; $$ LANGUAGE plpgsql;"

	triggersql = "CREATE TRIGGER testTrigger AFTER INSERT OR UPDATE ON ypb_"
	triggersql += tablename+" FOR EACH ROW EXECUTE PROCEDURE "+triggerName
	cursor = conn.cursor()
	try:
		cursor.execute(funsql)
		cursor.execute(triggersql)
		conn.commit()
		print("create trigger function and trigger success!")
	except BaseException: #no table named xxx,so create it!
		conn.rollback()
		print("create trigger function or trigger failed!,\noperate alredy rollback,nothing to do")

def initPostgres(conn,table):
	if(len(table)==0):
		return
	tables = table.split("#")
	for t in tables:
		createBackupTable(conn,t)
		createBackupTrigger(conn,t)




